#include <glib.h>

gboolean _traverse_str_str_func (gpointer key, gpointer value, gpointer data)
{
    g_print("key:%s, value:%s user_data:%s \n", (char *)key, (char *)value, (gchar *)data);
    return 0;
}

void _str_str_key_destroy_func(gpointer data)
{
    if(NULL != data) {
        g_free(data);
    }
}

void _str_str_value_destroy_func(gpointer data)
{
    if(NULL != data) {
        g_free(data);
    }
}

gint gtree_test_str_str_data(void)
{
    GTree *tree = NULL;
    gchar *val1 = NULL, *val2 = NULL;
    gchar *ori_key = NULL, *val3 = NULL;
    gboolean ret = FALSE;
    gint i = 0;

    tree = g_tree_new_full((GCompareDataFunc)strcmp,NULL,_str_str_key_destroy_func,_str_str_value_destroy_func);
    if(NULL == tree) {
        g_print("g_tree_new return NULL \n");
        return 0;
    }

    for(i=0; i<3; i++) {
        g_tree_insert(tree, (gpointer)g_strdup_printf("key-%d", i), (gpointer)g_strdup_printf("value-%d", i));
    }

    g_tree_foreach(tree, _traverse_str_str_func, "str-str");

    val1 = (gchar *)g_tree_lookup(tree, (gchar *)"key-1");
    if(NULL != val1) {
        g_print("value of key-1 is %s \n", val1);
    } else {
        g_print("can not find key-1 \n");
    }
    val2 = (gchar *)g_tree_lookup(tree, (gchar *)"key-9");
    if(NULL != val2) {
        g_print("value of key-9 is %s \n", val1);
    } else {
        g_print("can not find key-9 \n");
    }

    g_tree_foreach(tree, _traverse_str_str_func, "str-str-after-lookup");

    ret = g_tree_lookup_extended(tree, (gchar *)"key-1", (gpointer *)&ori_key, (gpointer *)&val3);
    if(ret) {
        g_print("found! ori_key:%s, value:%s \n", ori_key, val3);
    }

    g_tree_foreach(tree, _traverse_str_str_func, "str-str-after-lookup_extended");

    g_tree_destroy(tree);

    return 0;
}

gint main(gint argc, gchar **argv)
{
    gtree_test_str_str_data();

    return 0;
}